
import Util from './utils';
import Sessioin from './session';

class RequestBase {
    constructor({host, headers = {}, timeout = 5000}) {
        const sysInfo = uni.getAppBaseInfo();

        this.host = host;
        this.headers = headers;
        this.timeout = timeout;
        this.appVersion = `${sysInfo.appVersion}.${sysInfo.appVersionCode}`;

        this.addHeader({
            // 解决 SharedArrayBuffer 跨域问题
            'Cross-Origin-Embedder-Policy': 'require-corp',
            'Cross-Origin-Opener-Policy': 'same-origin',
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Allow-Origin': '*',

            'content-type': 'application/json',
            'x-app-version': this.appVersion,
            'x-platform': sysInfo.uniPlatform || '',
            'x-os': sysInfo.osName || '',
        });
    }

    setHost(host) {
        this.host = host;
    }

    addHeader(headers) {
        if (headers && typeof headers == 'object') {
            this.headers = Object.assign(this.headers, headers);
        }
    }

    setTimeout(timeout) {
        if (typeof timeout === 'number' && timeout > 0) {
            this.timeout = timeout;
        } else {
            console.error('请设置正确的timeout数值');
        }
    }

    request(options) {
        const { path, header } = options;
        const { sessionId, openid, uid, unionid } = Sessioin.getSession();

        return new Promise((resolve, reject) => {
            uni.request({
                ...options,
                url: this.host + path,
                timeout: this.timeout,
                header: Object.assign(this.headers, {
                    'x-appid': Sessioin.getAppid(),
                    'x-session-id': sessionId || '',
                    session: sessionId || '',
                    openid: openid || '',
                    uid: uid || '',
                    unionid: unionid || '',
                    ...(header || {})
                }),
                success: res => {
                    if (typeof res.data === 'object') {
                        const code = res.data?.code?.toUpperCase();

                        if (code === 'OK' || code === 'SUCCESS') {
                            resolve(res.data.data);
                        } else {
                            reject(res.data);
                        }
                    } else {
                        resolve(res.data);
                    }
                },
                fail: err => {
                    console.error('request error', err);
                    if (Util.skipError(err && JSON.stringify(err || {}))) return;

                    if (err?.errMsg?.includes('abort')) return;

                    uni.showModal({
                        title: '错误',
                        showCancel: false,
                        content: `服务器异常，请重试(${path})`
                    });
                    reject(err);
                },
            });
        });
    }

    get(opts) {
        return this.request({
            method: 'GET',
            ...opts
        });
    }

    post(opts) {
        return this.request({
            method: 'POST',
            ...opts
        });
    }

    put(opts) {
        return this.request({
            method: 'PUT',
            ...opts
        });
    }

    // 有兼容性问题
    // https://zh.uniapp.dcloud.io/api/request/request.html#request
    delete(opts) {
        return this.request({
            method: 'DELETE',
            ...opts
        });
    }
}

const UniappBaseRequest = new RequestBase({
    host: 'https://api.ali-fc.moapp.net.cn/service/uniapp_base',
    // host: 'https://dev.ali-fc.mozigu.net/service/uniapp_base',
    timeout: 20000
});

export {
    RequestBase,
    UniappBaseRequest
};
